<template>
  <div ref="editorContainer" class="tinymce-container"></div>
</template>

<script>
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver/theme';
import 'tinymce/icons/default/icons';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/link';
import 'tinymce/plugins/image';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/table';
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/fullscreen';
import 'tinymce/skins/ui/oxide/skin.min.css';
import 'tinymce/skins/content/default/content.min.css';

export default {
  name: 'TinymceEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: [Number, String],
      default: 400
    }
  },
  data() {
    return {
      editor: null
    };
  },
  mounted() {
    this.initEditor();
  },
  beforeDestroy() {
    this.destroyEditor();
  },
  watch: {
    value(newVal) {
      this.updateEditorContent(newVal);
    }
  },
  methods: {
    initEditor() {
      const self = this;
      tinymce.init({
        target: this.$refs.editorContainer,
        height: this.height,
        plugins: 'paste link image lists table wordcount fullscreen',
        toolbar: 'undo redo | formatselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table | fullscreen',
        skin: false,
        content_css: false,
        setup(editor) {
          self.editor = editor;
          
          // 初始化内容
          editor.setContent(self.value);
          
          // 内容变化时触发事件
          editor.on('change', () => {
            self.$emit('input', editor.getContent());
          });
          
          // 失去焦点时触发事件
          editor.on('blur', () => {
            self.$emit('blur', editor.getContent());
          });
        }
      });
    },
    destroyEditor() {
      if (this.editor) {
        tinymce.remove(this.editor);
        this.editor = null;
      }
    },
    updateEditorContent(content) {
      if (this.editor && content !== this.editor.getContent()) {
        this.editor.setContent(content);
      }
    }
  }
};
</script>

<style scoped>
.tinymce-container {
  width: 100%;
}
</style>    